package com.weetop.cfw.home_page.fragment

import android.content.Intent
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.coorchice.library.SuperTextView
import com.gyf.immersionbar.ImmersionBar
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.stx.xhb.xbanner.XBanner
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.HomePagePresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.ui.fragment.CommonBaseFragment
import com.weetop.cfw.base.view.HomePageView
import com.weetop.cfw.bean.*
import com.weetop.cfw.constants.Constants
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.event.UpdateUserInfoEvent
import com.weetop.cfw.home_page.activity.ChooseAddressActivity
import com.weetop.cfw.home_page.activity.SearchActivity
import com.weetop.cfw.home_page.activity.WorkshopWarehouseListActivity
import com.weetop.cfw.home_page.adapter.HomePageRecommendAppAdapter
import com.weetop.cfw.mine.activity.AudioFrequencyActivity
import com.weetop.cfw.mine.activity.CloudCurriculumActivity
import com.weetop.cfw.other.CommonWebViewActivity
import com.weetop.cfw.other.RichTextWebViewActivity
import com.weetop.cfw.utils.MMKVUtils
import com.weetop.cfw.widget.RoundRelativeLayout
import kotlinx.android.synthetic.main.fragment_home_page.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 首页界面
 */
class HomePageFragment : CommonBaseFragment(), View.OnClickListener, HomePageView,
    OnRefreshLoadMoreListener {

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.linearSearchHeader -> SearchActivity.startSearchActivity(
                activity as CommonBaseActivity,
                1
            )
            R.id.imageWorkshopWarehouseList -> ActivityUtils.startActivity(
                WorkshopWarehouseListActivity::class.java
            )
            R.id.imageCloudCurriculumLogo -> ActivityUtils.startActivity(CloudCurriculumActivity::class.java)
            R.id.imageAudioLogo -> ActivityUtils.startActivity(AudioFrequencyActivity::class.java)
            R.id.imageLogPerformanceLogo -> {
                RichTextWebViewActivity.startRichTextWebViewActivity(
                    context!!,
                    "日志绩效",
                    "https://www.zdzf.cn/",
                    true
                )
            }
            R.id.relativeListingService -> {
//                val intent = Intent(context, EnterpriseServiceActivity::class.java)
//                intent.putExtra(EnterpriseServiceActivity.ENTERPRISE_SERVICE_TYPE, 0)
//                ActivityUtils.startActivity(intent)
                RichTextWebViewActivity.startRichTextWebViewActivity(
                    context!!,
                    "上市服务",
                    appListingServiceStr
                )
            }
            R.id.relativeInvestmentPromotionService -> {
                if (context != null) {
                    RichTextWebViewActivity.startRichTextWebViewActivity(
                        context!!,
                        "融资服务",
                        "file:///android_asset/zirongfuwu.html",
                        true
                    )

                    //  CommonWebViewActivity.startCommonWebViewActivity(context!!,UrlConstants.financing_services_web_url)
                }
            }
            R.id.relativeIndustrialAndCommercialTaxation -> {
//                val intent = Intent(context, EnterpriseServiceActivity::class.java)
//                intent.putExtra(EnterpriseServiceActivity.ENTERPRISE_SERVICE_TYPE, 2)
//                ActivityUtils.startActivity(intent)
                RichTextWebViewActivity.startRichTextWebViewActivity(
                    context!!,
                    "工商财税",
                    appIndustrialAndCommercialTaxationStr
                )
            }
            R.id.linearAddressContainer -> startCityPicker()
        }
    }

    private lateinit var headerView: View

    private lateinit var homePageBanner: XBanner

    private lateinit var recommendAppAdapter: HomePageRecommendAppAdapter

    private lateinit var imageWorkshopWarehouseList: RelativeLayout
    private lateinit var imageCloudCurriculumLogo: ImageView
    private lateinit var imageAudioLogo: ImageView
    private lateinit var imageLogPerformanceLogo: ImageView

    private lateinit var relativeListingService: RoundRelativeLayout
    private lateinit var relativeInvestmentPromotionService: RoundRelativeLayout
    private lateinit var relativeIndustrialAndCommercialTaxation: RoundRelativeLayout

    private lateinit var locationListener: BDAbstractLocationListener//定位监听器

    private lateinit var locationClient: LocationClient//百度定位工具类

    private lateinit var homePagePresenterImp: HomePagePresenterImp

    private var locationCityName: String? = null//定位到的城市名称
    private var appListingServiceStr = ""//上市服务富文本
    private var appIndustrialAndCommercialTaxationStr = ""//工商财税富文本

    private var currentPageNumber: Int = 1//当前数据的页数
    private var totalCount: Int = 0//数据的总记录数
    private var isRefreshing: Boolean = false//当前是否处于刷新状态
    private var isLoadingMore: Boolean = false//当前是否处于加载更多状态

    private lateinit var recommendEmptyView: View

    private val recommendActivitiesList = ArrayList<AdvertisementBean.DataBean>()

    override fun getLayoutId() = R.layout.fragment_home_page

    override fun initView() {

        homePagePresenterImp = HomePagePresenterImp()
        homePagePresenterImp.attachView(this)

        headerView = View.inflate(context, R.layout.layout_home_page_header, null)
        recommendEmptyView = View.inflate(context, R.layout.recommend_rv_empty_data, null)

        imageWorkshopWarehouseList = headerView.findViewById(R.id.imageWorkshopWarehouseList)
        homePageBanner = headerView.findViewById(R.id.homePageBanner)
        imageCloudCurriculumLogo = headerView.findViewById(R.id.imageCloudCurriculumLogo)
        imageAudioLogo = headerView.findViewById(R.id.imageAudioLogo)
        imageLogPerformanceLogo = headerView.findViewById(R.id.imageLogPerformanceLogo)
        relativeListingService = headerView.findViewById(R.id.relativeListingService)
        relativeInvestmentPromotionService =
            headerView.findViewById(R.id.relativeInvestmentPromotionService)
        relativeIndustrialAndCommercialTaxation =
            headerView.findViewById(R.id.relativeIndustrialAndCommercialTaxation)
    }

    override fun initData() {

        homePageRefresh.setOnRefreshLoadMoreListener(this)

        locationCurrentCity()//定位当前城市

        setViewsOnClickListener(
            this,
            linearSearchHeader,
            imageWorkshopWarehouseList,
            imageCloudCurriculumLogo,
            imageAudioLogo,
            imageLogPerformanceLogo,
            relativeListingService,
            relativeInvestmentPromotionService,
            relativeIndustrialAndCommercialTaxation,
            linearAddressContainer
        )

        userVisibleHint = true

        if (MMKVUtils.getToken().isNotEmpty()) {//如果用户登录了，再进行网络请求
            homePagePresenterImp.getPersonalInfoData(this)
        }
        homePagePresenterImp.getListingServiceData(this)
        homePagePresenterImp.getIndustrialAndCommercialTaxationData(this)

        recommendAppAdapter =
            HomePageRecommendAppAdapter(R.layout.layout_item_recommend_app, recommendActivitiesList)
        recommendAppAdapter.setHeaderView(headerView)
        recommendAppAdapter.setOnItemClickListener { _, _, position ->
//            if (recommendActivitiesList[position].isJump == 0) {
            homePagePresenterImp.getRecommendInfo(
                this,
                recommendActivitiesList[position].infoid
            )
//            } else {
//                CommonWebViewActivity.startCommonWebViewActivity(
//                    context!!,
//                    recommendActivitiesList[position].link
//                )
//            }
        }
        recommendAppRV.adapter = recommendAppAdapter
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveUpdateUserInfoEvent(updateUserInfoEvent: UpdateUserInfoEvent) {

        LogUtils.eTag(
            "recommendActivitiesListGetSuccess::updateUserInfoEvent",
            "======================"
        )
        homePagePresenterImp.getPersonalInfoData(this)
    }

    override fun onPause() {
        super.onPause()
        homePageBanner.stopAutoPlay()
    }

    override fun onResume() {
        super.onResume()
        homePageBanner.startAutoPlay()
    }


    override fun lazyLoadData() {
        ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(false)
            .statusBarDarkFont(false).init()
    }

    /**
     * 打开城市选择界面
     */
    private fun startCityPicker() {
        if (activity != null) {
            val intent = Intent(context, ChooseAddressActivity::class.java)
            intent.putExtra(ChooseAddressActivity.CURRENT_LOCATION_CITY_NAME, locationCityName)
            startActivity(intent)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveHotSitesBean(hotSitesDataBean: HotSitesBean.DataBean) {
        LogUtils.eTag("recommendActivitiesListGetSuccess::", hotSitesDataBean.toString())

        textCurrentCity.text = hotSitesDataBean.sitename
        Constants.cityId = hotSitesDataBean.cityid
        Constants.siteId = hotSitesDataBean.siteid
        Constants.cityName = hotSitesDataBean.cityname

        homePageRefresh.autoRefresh()

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveHotSitesBean(sdataBean: AllSubSiteListBean.DataBean.SdataBean) {
        LogUtils.eTag("recommendActivitiesListGetSuccess++++++", sdataBean.toString())

        if (sdataBean.siteid == -1) {
            locationCurrentCity()//定位当前城市
        } else {
            textCurrentCity.text = sdataBean.sitename
            Constants.cityId = sdataBean.cityid
            Constants.siteId = sdataBean.siteid
            Constants.cityName = sdataBean.cityname
            homePageRefresh.autoRefresh()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //注销定位监听器
        locationClient.unRegisterLocationListener(locationListener)
        homePagePresenterImp.detachView()
    }

    /**
     * 定位当前城市
     */
    override fun locationCurrentCity() {
        locationClient = LocationClient(activity!!.applicationContext)
        locationListener = object : BDAbstractLocationListener() {
            override fun onReceiveLocation(p0: BDLocation?) {
                if (p0 != null) {
                    locationCityName = p0.city
                    Constants.cityName = p0.city
                    textCurrentCity.text = locationCityName//获取到当前城市并展示
                    homePagePresenterImp.getCityIdByCityName(this@HomePageFragment, p0.city)
                }
            }
        }
        locationClient.registerLocationListener(locationListener)
        val option = LocationClientOption()
        option.setIsNeedAddress(true)
        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true

        locationClient.locOption = option
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        locationClient.start()
    }

    /**
     * 根据城市名称获取cityId成功
     */
    override fun getCityIdSuccess(cityIdBean: CityIdBean?) {
        if (cityIdBean != null) {
            Constants.cityId = cityIdBean.cityid
            Constants.siteId = cityIdBean.siteid
            homePagePresenterImp.getHomePageBannerExData(this, 1)
            homePagePresenterImp.getRecommendActivitiesListEx(this, 1)
            LogUtils.d("cityid", Constants.cityId)
            LogUtils.d("siteId", Constants.siteId)
        }
    }

    /**
     * 用户信息获取成功
     */
    override fun personalInfoGetSuccess(personalInfoBean: PersonalInfoBean?) {
        if (personalInfoBean != null) {
            textHeadImgLogo.setUrlImage("${UrlConstants.baseUrl}${personalInfoBean.face}")
        }
    }

    /**
     * 上市服务富文本获取成功
     */
    override fun listingServiceDataGetSuccess(singlePageIntroduceBean: SinglePageIntroduceBean?) {
        if (singlePageIntroduceBean != null) {
            if (singlePageIntroduceBean.content.contains("http")) {
                appListingServiceStr = singlePageIntroduceBean.content;
            } else
                appListingServiceStr = singlePageIntroduceBean.content.replace(
                    "/Upload/image/",
                    UrlConstants.baseUrl + "Upload/image/"
                )
        }
    }

    /**
     * 工商财税富文本获取成功
     */
    override fun industrialAndCommercialTaxationDataFetSuccess(singlePageIntroduceBean: SinglePageIntroduceBean?) {
        if (singlePageIntroduceBean != null) {
            appIndustrialAndCommercialTaxationStr = singlePageIntroduceBean.content
        }
    }

    /**
     * 广告Banner数据获取成功
     */
    override fun advertisementBannerDataGetSuccess(advertisementBean: AdvertisementBean?) {
        if (advertisementBean != null) {
            homePageBanner.setBannerData(R.layout.layout_banner_item_image, advertisementBean.data)

            homePageBanner.loadImage { _, _, view, position ->
                val textBannerItemImage = view.findViewById<SuperTextView>(R.id.textBannerItemImage)
                textBannerItemImage.setUrlImage(advertisementBean.data[position].xBannerUrl)
                textBannerItemImage.setOnClickListener {
//                    CommonWebViewActivity.startCommonWebViewActivity(
//                        context!!,
//                        advertisementBean.data[position].link
//                    )
                    if (advertisementBean.data[position].isJump == 0) {
                        homePagePresenterImp.getRecommendInfo(
                            this,
                            advertisementBean.data[position].infoid
                        )
                    } else {
                        CommonWebViewActivity.startCommonWebViewActivity(
                            context!!,
                            advertisementBean.data[position].link
                        )
                    }
                }
            }
        }
    }

    /**
     * 推荐活动列表获取成功
     */
    override fun recommendActivitiesListGetSuccess(advertisementBean: AdvertisementBean?) {
        if (advertisementBean != null) {
            if (isRefreshing) {
                recommendActivitiesList.clear()
                recommendActivitiesList.addAll(advertisementBean.data)
                recommendAppAdapter.notifyDataSetChanged()
                homePageRefresh.finishRefresh(true)
                if (advertisementBean.data.size > 0) {
                    currentPageNumber = 1
                }
                if (advertisementBean.data.size == 0) {
                    recommendAppAdapter.setFooterView(recommendEmptyView)
                    homePageRefresh.setEnableLoadMore(false)
                } else {
                    homePageRefresh.setEnableLoadMore(true)
                    recommendAppAdapter.removeAllFooterView()
                }
                isRefreshing = false
                return
            }
            if (isLoadingMore) {
                recommendActivitiesList.addAll(advertisementBean.data)
                recommendAppAdapter.notifyDataSetChanged()
                homePageRefresh.finishLoadMore(true)
                if (advertisementBean.data.size > 0) {
                    currentPageNumber += 1
                }
                isLoadingMore = false
                return
            }
            recommendActivitiesList.clear()
            recommendActivitiesList.addAll(advertisementBean.data)
            recommendAppAdapter.notifyDataSetChanged()
            if (advertisementBean.data.size == 0) {
                recommendAppAdapter.setFooterView(recommendEmptyView)
                homePageRefresh.setEnableLoadMore(false)
            } else {
                recommendAppAdapter.removeAllFooterView()
                homePageRefresh.setEnableLoadMore(true)
            }
        }
    }

    /**
     * 推荐活动列表详情获取成功
     */
    override fun recommendInfoSuccess(recommendInfoBean: HomeRecommendInfoBean?) {
        if (recommendInfoBean != null && !StringUtils.isEmpty(recommendInfoBean.content)) {
            CommonWebViewActivity.startCommonWebViewContentActivity(
                context!!,
                recommendInfoBean.content.replace(
                    "/Upload/image/",
                    UrlConstants.baseUrl + "Upload/image/"
                ),
                recommendInfoBean.phone
            )
        }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        if (recommendActivitiesList.size >= totalCount) {
            showNativeShortToast("暂无更多数据")
            homePageRefresh.finishLoadMoreWithNoMoreData()
        } else {
            isLoadingMore = true
            homePagePresenterImp.getRecommendActivitiesListEx(this, currentPageNumber + 1)
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        isRefreshing = true
        if (MMKVUtils.getToken().isNotEmpty()) {//如果用户登录了，再进行网络请求
            homePagePresenterImp.getPersonalInfoData(this)
        }
        homePagePresenterImp.getListingServiceData(this)
        homePagePresenterImp.getIndustrialAndCommercialTaxationData(this)
        homePagePresenterImp.getHomePageBannerExData(this, 1)
        homePagePresenterImp.getRecommendActivitiesListEx(this, 1)
    }
}